<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class controller_role extends lib_controller
{
	public function init($action)
	{
		$operations = lib_toolkit::getOperations();
		
		if($action == 'doRoleList' || $action == 'doViewRole' || $action == 'doAddRole' || $action == 'addRolePage' || $action == 'doDeleteRole' || $action == 'doEditRole')
		{
			if(!in_array('doRoleList',$operations))
			{
				die("Permission denied.");
			}
		}
		
		if($action == 'doRoleRight' || $action == 'doUpdateRoleRight')
		{
			if(!in_array('doRoleRight', $operations))
			{
				die("Permission denied.");
			}
		}
		
		if($action == 'doAssignRole' || $action == 'doUpdateAssignRole')
		{
			if(!in_array('doAssignRole', $operations))
			{
				die("Permission denied.");
			}
		}
		
		lib_toolkit::filterBrowserScript();
	}
	
	public function doRoleList()
	{
		$_mysql_ = $this->_mysql_;
		$roles = $_mysql_->findAll("rights");
		
		if(empty($roles))//没有角色，用户不能执行任何操作
		{
			die("Permission denied.");
		}
		else
		{
			$this->assign('roles',$roles);
		}
	}
	
	public function doViewRole()
	{
		$r_id = $_GET['r_id'];
		$isRmpty = false; 
		
		if(empty($r_id)) $r_id = 0;
		
		$_mysql_ = $this->_mysql_;
		$role = $_mysql_->find("rights","r_id = $r_id");
		
		$isEmpty = empty($role) ? true : false;
		if(!($role['r_role'] == 'admin' || $role['r_role'] == 'unassign'))//admin和unassign角色为内置角色只能查看，其他角色不能查看，在编辑中查看
		{
			@header("Location: index.php?_m=role&_a=doRoleList");
			die;
		}
		
		$this->assign('role', $role);
		$this->assign('isEmpty', $isEmpty);
	}
	
	public function addRolePage()
	{
		$this->assign('next_controller','role');
		$this->assign('next_action', 'doAddRole');
	}
	
	public function doAddRole()
	{
		$this->_layout = 'response';
		$_mysql_ = $this->_mysql_;
		$_xml_ = $this->_xml_;
		$prefix = $_xml_->getConfig('data/prefix');
		$_session_ = $this->_session_;
		$u_name = $_session_->getSession('u_name');
		
		$r_alias = $_POST['r_alias'];
		if(empty($r_alias))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Role name is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
		$r_alias = trim($r_alias);
		$roles = $_mysql_->findAll('rights');
		$id = '';
		foreach($roles as $v)
		{
			if($k == 0)
			{
				$id = $v['r_id'];
			}
			else
			{
				if($v['r_id'] > $i)
				{
					$i = $v['r_id'];
				}
			}
			
			if($v['r_alias'] == $r_alias)
			{
				$res_arr = array('result' => 'error','errmsg' =>"$r_alias has existed.");
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
		}
		$id++;
		$operations = 'doSubmitTemplate';//创建角色时默认赋予的操作权限
		$new_role = "role$id";
		$_mysql_->customSql("INSERT INTO {$prefix}rights (r_role,r_operation,r_alias,r_desc) VALUES ('$new_role','$operations','$r_alias','{$_POST['r_desc']}')");
		
		$current_time = time();
		$ip =$_SERVER['REMOTE_ADDR'];
		 
		$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('add role',$current_time,'$ip','add role:$new_role','{$u_name}')");
		$res_arr = array('result' => 'ok','sucmsg' =>"Add role successfully.");
		$res_str = json_encode($res_arr);
		$this->assign('res_str', $res_str);
		return 'result';
	}
	
	public function doDeleteRole()
	{
		$this->_layout = 'response';
		
		$_mysql_ = $this->_mysql_;
		$_xml_ = $this->_xml_;
		$_session_ = $this->_session_;
		
		$prefix = $_xml_->getConfig('data/prefix');
		$current_time = time();
		$ip = $_SERVER['REMOTE_ADDR'];
		$operator = $_session_->getSession('u_name');
		$user_role = array();
		
		$r_id = intval($_GET['id']);
		
		if(empty($r_id))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		else
		{
			$result = $_mysql_->find("rights","r_id = $r_id");
			if(empty($result) || ($result['r_role'] == 'admin') || ($result['r_role'] == 'unassign'))//admin和unassign角色不能删除
			{
				$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			else
			{
				$_mysql_->customSql("DELETE FROM {$prefix}rights WHERE r_id = $r_id");
				
				//删除用户中的此角色
				$users = $_mysql_->findAll('users');
				foreach($users as $v)
				{
					$user_role = explode(',',$v['u_role']);
					$role_str = '';
					foreach($user_role as $v1)
					{
						if($v1 != $result['r_role'])
						{
							$role_str .= $v1.',';
						}
					}
					$role_str = substr($role_str,0,strlen($role_str)-1);
					if(empty($role_str)) $role_str = 'unassign';
					
					$_mysql_->customSql("UPDATE {$prefix}users SET u_role = '$role_str' WHERE u_id = {$v['u_id']}");
				}
				
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('Delete role',$current_time,'$ip','Delete role: {$result['r_role']}.','$operator')");
				$res_arr = array('result' => 'ok','sucmsg' => 'Delete role successfully.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
		}
	}
	
	public function editRolePage()
	{
		$_mysql_ = $this->_mysql_;
		
		$r_id = intval($_GET['r_id']);
		if(empty($r_id))
		{
			@header("Location: index.php?_m=role&_a=doRoleList");
			die;
		}
		else
		{
			$role = $_mysql_->find("rights","r_id = $r_id");
			if(empty($role))
			{
				@header("Location: index.php?_m=role&_a=doRoleList");
				die;
			}
			else
			{
				$this->assign('next_controller', 'role');
				$this->assign('next_action', 'doUpdateRole');
				$this->assign('role', $role);
			}
		}
	}
	
	public function doUpdateRole()
	{
		$this->_layout = 'response';
		
		$_xml_ = $this->_xml_;
		$prefix = $_xml_->getConfig('data/prefix');
		$_mysql_ = $this->_mysql_;
		$_session_ = $this->_session_;
		$u_name = $_session_->getSession('u_name');
		$r_desc = $_POST['r_desc'];
		
		if(empty($_POST['r_alias']) || empty($_POST['r_id']))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		else
		{
			$r_alias = trim($_POST['r_alias']);
			$r_id = trim($_POST['r_id']);
			$r_id = intval($r_id);
			
			$role = $_mysql_->find('rights',"r_id = $r_id");
			if($role['r_role'] == 'admin' || $role['r_role'] == 'unassign')//admin和unassign不允许被修改
			{
				$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
				$res_str = json_encode($res_arr);
				$this->assign('res_str', $res_str);
				return 'result';
			}
			
			$other = $_mysql_->findAll("rights","r_id <> $r_id");
			foreach($other as $v)
			{
				if($v['r_alias'] == $r_alias)//角色别名不允许修改成与其他角色别名相同
				{
					$res_arr = array('result' => 'error','errmsg' => 'This role name has existed.');
					$res_str = json_encode($res_arr);
					$this->assign('res_str', $res_str);
					return 'result';
				}
			}
			
			$_mysql_->customSql("UPDATE {$prefix}rights SET r_alias = '$r_alias',r_desc = '$r_desc' WHERE r_id = $r_id");
			$current_time = time();
			$ip = $_SERVER['REMOTE_ADDR'];
			
			$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('Update role',$current_time,'$ip','Update role: {$role['r_role']}.','$u_name')");
			$res_arr = array('result' => 'ok','sucmsg' => 'Update role successfully.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
	}
	
	public function doRoleRight()
	{
		$_mysql_ = $this->_mysql_;
		
		$roles_arr = $_mysql_->findAll('rights');
		$operations_arr = $_mysql_->findAll('operations');
		
		if(empty($roles_arr) || empty($operations_arr))
		{
			die("Data error.");
		}
		
		$this->assign('roles_arr', $roles_arr);
		$this->assign('operations_arr', $operations_arr);
		$this->assign('next_controller', 'role');
		$this->assign('next_action', 'doUpdateRoleRight');	
	}
	
	public function doUpdateRoleRight()
	{
		$this->_layout = 'response';
		$_mysql_ = $this->_mysql_;
		$_xml_ = $this->_xml_;
		$_session_ = $this->_session_;
		$prefix = $_xml_->getConfig('data/prefix');
		$current_time = time();
		$ip = $_SERVER['REMOTE_ADDR'];
		$operator = $_session_->getSession('u_name');
		
		$role_name = '';
		$role_arr = '';
		$role_arr_count = '';
		$tmp_arr = '';//[admin] => array(operation1,operation2) [unassign] => array(operation3,operation4)
		foreach($_POST as $k => $v)
		{
			if($k == '_m' || $k == '_a') continue;
			//--------------获取角色名(非别名)-----------------
			$role_arr = explode('_',$k);
			$role_arr_count = count($role_arr);
			$role_name = '';
			
			if($role_arr_count == 2) $role_name = $role_arr[0];
			if($role_arr_count > 2)//应对test_leader_xxx这样的问题
			{
				for($i = 0;$i < $role_arr_count - 1;$i++)
				{
					$role_name .= $role_arr[$i].'_';
				}
				$role_name = substr($role_name,0,strlen($role_name) - 1);
			}
			//--------------获取角色名(非别名)-----------------
			$tmp_arr[$role_name] .= $v.',';
		}
		
		if(empty($tmp_arr))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
		//-------------------获取角色列表更新数据表--------------
		$roles_arr = array();
		$roles_arr = $_mysql_->findAll('rights');//角色中没有人任何操作是不会post上来，所以用此列表来找出post不上来的情况
		$operations = '';
		foreach($roles_arr as $v)
		{
			if($v['r_role'] == 'admin' || $v['r_role'] == 'unassign') continue;//admin和unassign不允许修改
			
			 if(array_key_exists($v['r_role'],$tmp_arr))
			 {
			 	$operations = substr($tmp_arr[$v['r_role']],0,strlen($tmp_arr[$v['r_role']]) - 1);
				$_mysql_->customSql("UPDATE {$prefix}rights SET r_operation = '$operations' WHERE r_role = '{$v['r_role']}'");
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('update role rights',$current_time,'$ip','update {$v['r_role']} rights:$operations','$operator')");
			 }
			 else//某个角色没有任何操作则界面没有post数据
			 {
			 	$_mysql_->customSql("UPDATE {$prefix}rights SET r_operation = '' WHERE r_role = '{$v['r_role']}'");
			 	$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('update role rights',$current_time,'$ip','update {$v['r_role']} rights as empty','$operator')");
			 }
		}
		//-------------------获取角色列表更新数据表--------------
		$res_arr = array('result' => 'ok','sucmsg' => 'Update role rights successfully.');
		$res_str = json_encode($res_arr);
		$this->assign('res_str', $res_str);
		return 'result';
	}
	
	public function doAssignRole()
	{
		$_mysql_ = $this->_mysql_;
		
		$users = $_mysql_->findAll('users',"u_active = 1");
		$roles = $_mysql_->findAll("rights");
		
		if(empty($users) || empty($roles))
		{
			die("Data error.");
		}
		
		$this->assign('users',$users);
		$this->assign('roles',$roles);
		$this->assign('next_controller','role');
		$this->assign('next_action','doUpdateAssignRole');
	}
	
	public function doUpdateAssignRole()
	{
		$this->_layout = 'response';
		
		$_session_ = $this->_session_;
		$_mysql_ = $this->_mysql_;
		$_xml_ = $this->_xml_;
		
		$prefix = $_xml_->getConfig('data/prefix');
		$current_time = time();
		$ip = $_SERVER['REMOTE_ADDR'];
		$operator = $_session_->getSession('u_name');
		
		$tmp_arr = array();
		$tmp_arr1 = array();
		$user = '';
		
		if(empty($_POST))
		{
			$res_arr = array('result' => 'error','errmsg' => 'Data is empty.');
			$res_str = json_encode($res_arr);
			$this->assign('res_str', $res_str);
			return 'result';
		}
		
		foreach($_POST as $k => $v)
		{
			if($k == '_m' || $k == '_a') continue;
			
			$tmp_arr1 = explode('_',$k);
			$user = $tmp_arr1[0];
			
			$tmp_arr[$user] .= $v.',';
		}
		
		$user = '';
		$users = $_mysql_->findAll('users','u_active = 1');
		foreach($users as $v)
		{
			if($v['u_name'] == 'admin') continue;
			if(array_key_exists($v['u_name'],$tmp_arr))
			{
				$role_str = substr($tmp_arr[$v['u_name']],0,strlen($tmp_arr[$v['u_name']]) - 1);
				$_mysql_->customSql("UPDATE {$prefix}users SET u_role = '$role_str' WHERE u_name = '{$v['u_name']}'");
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('update user roles',$current_time,'$ip','update user roles:$role_str','$operator')");
			}
			else
			{
				$_mysql_->customSql("UPDATE {$prefix}users SET u_role = 'unassign' WHERE u_name = '{$v['u_name']}'");//角色不选择则默认为unassign
				$_mysql_->customSql("INSERT INTO {$prefix}logs (log_operation,log_time,log_ip,log_desc,log_operator) VALUES ('update user roles',$current_time,'$ip','update user roles:unassign','$operator')");
			}
		}
		
		$res_arr = array('result' => 'ok','sucmsg' => 'Update user roles successfully.');
		$res_str = json_encode($res_arr);
		$this->assign('res_str', $res_str);
		return 'result';
	}
}
?>